package net.realsee.framework.interceptor;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import net.realsee.common.constant.Constants;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 日志拦截器
 * 添加链路ID
 *
 * @author realsee
 * @version 1.0.0
 */
public class LogInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String tid = IdUtil.fastSimpleUUID();
        if (StrUtil.isNotBlank(request.getHeader(Constants.TRACE_ID))) {
            tid = request.getHeader(Constants.TRACE_ID);
        }
        MDC.put(Constants.TRACE_ID, tid);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        MDC.remove(Constants.TRACE_ID);
    }

}
